package cn.thornbird.orgsync.service.impl;

import cn.thornbird.orgsync.entity.User;
import cn.thornbird.orgsync.entity.VerificationCode;
import cn.thornbird.orgsync.exception.NotFoundException;
import cn.thornbird.orgsync.model.PageList;
import cn.thornbird.orgsync.model.combined.VerificationCodeObject;
import cn.thornbird.orgsync.repository.UserRepository;
import cn.thornbird.orgsync.repository.VerificationCodeRepository;
import cn.thornbird.orgsync.repository.specification.VerificationCodeSpecification;
import cn.thornbird.orgsync.service.VerificationCodeService;
import cn.thornbird.orgsync.vo.request.VerificationCodeQueryRequest;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class VerificationCodeServiceImpl extends BaseService<VerificationCodeRepository, VerificationCode>
        implements VerificationCodeService {

    private final VerificationCodeRepository verificationCodeRepository;

    private final UserRepository userRepository;

    @Override
    public VerificationCodeObject find(String id) throws NotFoundException {
        VerificationCodeObject verificationCodeObject = new VerificationCodeObject();
        VerificationCode verificationCode = findFirstById(verificationCodeRepository, id);
        User user = userRepository.findFirstByMobile(verificationCode.getMobile());
        verificationCodeObject.setVerificationCode(verificationCode);
        verificationCodeObject.setUser(user);
        return verificationCodeObject;
    }

    @Override
    public PageList<VerificationCode> query(VerificationCodeQueryRequest verificationCodeQueryRequest,
                                            Integer pageNumber, Integer pageSize) {
        Sort sort = Sort.by(Sort.Order.desc("createdAt"));
        Pageable pageable = PageList.generatePageable(pageNumber, pageSize, sort);
        Page<VerificationCode> page = verificationCodeRepository.findAll(
                new VerificationCodeSpecification(verificationCodeQueryRequest), pageable);
        return PageList.convertPage(page);
    }

}
